using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.DataControls
{
    [System.ComponentModel.Designer(typeof(TemplateDataSourceDesigner))]
    [System.Web.UI.ToolboxData("<{0}:TemplateDataSource runat=server/>")]
    public class TemplateDataSource : GenericDataSource<Bll.Template>
    {

        public enum Fields
        {
            Id,
            SiteId,
            Name,
            ConcurencyId
        }

        protected override Acms.Bll.Template PopulateData(UpdateAction action, System.Collections.IDictionary keys, System.Collections.IDictionary values, System.Collections.IDictionary oldValues)
        {
            Bll.Template tmp = null;
            byte[] concurencyId = null;
            if (action == UpdateAction.Insert)
            {
                tmp = Bll.Template.CreateInstance();
            }
            else
            {
                int id = GetValue<int>(Fields.Id, keys);
                concurencyId = GetValue<byte[]>(Fields.ConcurencyId, keys);
                tmp = Bll.Template.GetById(id);
            }

            if (tmp != null)
            {
                tmp.CheckConcurent(concurencyId);

                if (RequiresUpdate<int>(Fields.SiteId, values, oldValues))
                {
                    tmp.SiteId = GetValue<int>(Fields.SiteId, values);
                }
                if (RequiresUpdate<string>(Fields.Name, values, oldValues))
                {
                    tmp.Name = GetValue<string>(Fields.Name, values);
                }
            }

            return tmp;
        }

        protected override int SaveChanges(Acms.Bll.Template item)
        {
            item.Update();
            return 1;
        }

        protected override int Delete(Acms.Bll.Template item)
        {
            item.Delete();
            return 1;
        }

        protected override void AddInsertedKey(Acms.Bll.Template item, System.Collections.IDictionary values)
        {
            values[Fields.Id.ToString()] = item.Id;
        }

    }

    public class TemplateDataSourceDesigner : GenericDataSourceDesigner<Bll.Template>
    {
        protected override Acms.Bll.Template GetDesignTimeItem(int index)
        {
            Random rnd = new Random(index);
            string[] names = new string[]{"Home Page Template", "Article Template", "Image Template", "Section Template", "Blog Template"};
            Bll.Template tmp = Acms.Bll.Template.CreateInstance();
            tmp.Name = names[rnd.Next(0, names.Length)];
            tmp.SiteId = 1;
            return tmp;
        }
    }
}
